<?php
class ManageArticlesController
	extends MyApplicationController
{
	private $o_subNavi;
	public function start()
	{
		if(ClaycodeLogin::get()->isLogged() == true){
			$this->viewArticles();
		}else{
			header('location:' . fw_util_buildUrl('Login', '', true, false));
		}
	}
	
	public function addArticle()
	{
		parent::start();
		parent::showNavi();
		$this->getSubNavi();
		$o_addArticleForm = new ClaycodeForm('addArticle');
		
		$this->registry->template->s_mainAppDisplay = $o_addArticleForm->getFormHtml();
		$this->registry->template->show('Skeleton.php');
		
	}
	
	public function viewArticles()
	{
		parent::start();
		parent::showNavi();
		$this->getSubNavi();
		$this->registry->template->s_mainAppDisplay = $this->getViewArticlesHtml();
		$this->registry->template->show('Skeleton.php');
	}
	
	public function updateArticle()
	{
		$s_encryptedArticleId = $_GET['articleId'];
		$i_articleId = EncryptionHandler::get()->doDecrypt($s_encryptedArticleId);
		$o_article = $this->o_em->find('Article', $i_articleId);
		$s_articleTitle = $o_article->getArticleTitle();
		$s_articleContent = $o_article->getArticleContent();
		
		$o_updateArticleForm = new ClaycodeForm('updateArticle');
		$o_updateArticleForm->setFieldValue('articleTitle', $s_articleTitle);
		$o_updateArticleForm->setFieldValue('articleContent', $s_articleContent);
		$o_updateArticleForm->setFieldValue('articleId', $s_encryptedArticleId);
		parent::start();
		parent::showNavi();
		$this->getSubNavi();
		//note add the i_articleId to the hidden fields then configure the form
		$this->registry->template->s_mainAppDisplay = $o_updateArticleForm->getFormHtml();
		$this->registry->template->show('Skeleton.php');
	}
	
	public function deleteArticle()
	{
		$i_articleId = $_GET['articleId'];
		$i_articleId = EncryptionHandler::get()->doDecrypt($i_articleId);
		$o_article = $this->o_em->find('Article', (int)$i_articleId);
		try {
			$this->o_em->remove($o_article);
			$this->o_em->flush();
		} catch (Exception $e) {
		}
		
		
		fw_util_redirect('ViewArticles');
	}
	
	private function getSubNavi()
	{
		$arr_options = array(
					'pretty_urls'=> true,
					'is_sub_navi'=> false,
		);
		//$arr_subApps = $this->arr_appConf['sub_applications'];
		
		$arr_subApps = array(
			array(
				'app_ident'=> 'AddArticle',
				'app_display_name'=> 'Add Article',
				'controller_class'=> 'ManageArticlesController',
				'controller_class_alias'=> 'addArticleAlias',
				'hidden'=> false
			),
			
			array(
				'app_ident'=> 'ViewArticles',
				'app_display_name'=> 'View Articles',
				'controller_class'=> 'ManageArticlesController',
				'controller_class_alias'=> 'viewArticlesAlias',
				'hidden'=> false
			)
		);
		
		$this->o_subNavi = new ClaycodeNaviMenu($arr_subApps, $arr_options);
		$this->registry->template->s_subNavi = $this->o_subNavi->getNaviHtml();
		
	}
	
	
	//form handler function
	public function handleAddArticleForm()
	{
		$o_addArticleForm = new ClaycodeForm('addArticle');
		$o_addArticleForm->validateForm();
		if(count($o_addArticleForm->getFormErrors()) == 0){
			$arr_inputVals = $o_addArticleForm->getInputValues();
			$s_articleContent = htmlspecialchars($arr_inputVals['articleContent'], ENT_QUOTES);
			$s_articleTitle = htmlspecialchars($arr_inputVals['articleTitle'], ENT_QUOTES);
			$i_userId = EncryptionHandler::get()->doDecrypt(ClaycodeLogin::get()->getCredentials());
			//find the user that wrote it, currently logged user
			$o_articleWriter = $this->o_em->find('User',(int) $i_userId);
			$o_newArticle = new Article();
			$o_newArticle->setWriter($o_articleWriter);
			$o_newArticle->setArticleTitle($s_articleTitle);
			$o_newArticle->setArticleContent($s_articleContent);
			$o_newArticle->setCreateDate(new \DateTime("now"));
			//persist it in db
			$this->o_em->persist($o_newArticle);
			$this->o_em->flush();

			fw_util_redirect('ViewArticles');
		}else{
			parent::start();
			parent::showNavi();
			$this->getSubNavi();
			$this->registry->template->s_mainAppDisplay = $o_addArticleForm->getFormHtml();
			$this->registry->template->show('Skeleton.php');
		}
		
	}
	
	/**
	 * view articles
	 * Enter description here ...
	 */
	private function getViewArticlesHtml()
	{
		$arr_writtenArticles = $this->o_em->getRepository('Article')->getArticles();
		
		$s_viewArticlesHtml = '<table id="viewArticles">';
		
		$s_viewArticlesHtml .= '<thead>';
		$s_viewArticlesHtml .= '<tr>';
		$s_viewArticlesHtml .= '<th>written by</th>';
		$s_viewArticlesHtml .= '<th>article title</th>';
		$s_viewArticlesHtml .= '<th>date written</th>';
		$s_viewArticlesHtml .= '<th>remove</th>';
		$s_viewArticlesHtml .= '</tr>';
		$s_viewArticlesHtml .= '</thead>';
		/*
		$s_viewArticlesHtml .= '<tbody>';
			if(!empty($arr_writtenArticles)){
				$arr_updateArticleAppConf = Claycode_configuration::getInstance()->getAppConfArray('updateArticleAlias');
				$arr_deleteArticleAppConf = Claycode_configuration::getInstance()->getAppConfArray('deleteArticleTest');
				foreach($arr_writtenArticles as $o_writtenArticle)
				{
					$s_articleId = EncryptionHandler::get()->doEncrypt($o_writtenArticle->getId());
					$s_changeArticleUrl = fw_util_buildUrl($arr_updateArticleAppConf['controller_class_alias'], $this->arr_appConf['controller_class_alias'], true, true);
					$s_changeArticleUrl .= '/' . 'articleId' . '/' . $s_articleId;
					$s_deleteArticleUrl = fw_util_buildUrl($arr_deleteArticleAppConf['controller_class_alias'], $this->arr_appConf['controller_class_alias'],  true, true);
					$s_deleteArticleUrl .= '/' . 'articleId' . '/' . $s_articleId;
					
					$s_viewArticlesHtml .= '<tr>';
					$s_viewArticlesHtml .= '<td>' . $o_writtenArticle->getWriter()->getUserName() . '</td>';
					$s_viewArticlesHtml .= '<td><a href="'. $s_changeArticleUrl .'">' . $o_writtenArticle->getArticleTitle() . '</a></td>';
					$s_viewArticlesHtml .= '<td>' . $o_writtenArticle->getCreateDate()->format('m/d/Y H:m:s') . '</td>';
					$s_viewArticlesHtml .= '<td><a href="'. $s_deleteArticleUrl .'">remove</a></td>';
					$s_viewArticlesHtml .= '</tr>';
				}
			}
		*/
		$s_viewArticlesHtml .= '<tr><td colspan="5" class="dataTables_empty">Loading data from server</td></tr>';
		
		$s_viewArticlesHtml .= '</tbody>';
		
		$s_viewArticlesHtml .= '</table>';
		
		return $s_viewArticlesHtml;
	}
	
	
	public function handleUpdateArticleForm()
	{
		$o_updateArticleForm = new ClaycodeForm('updateArticle');
		$o_updateArticleForm->validateForm();
		if(count($o_updateArticleForm->getFormErrors()) == 0){
			$arr_postVals = $o_updateArticleForm->getInputValues();
			$i_articleId = EncryptionHandler::get()->doDecrypt($arr_postVals['articleId']);
			
			$o_articleToUpdate = $this->o_em->find('Article',(int) $i_articleId);
			$o_articleToUpdate->setArticleTitle(htmlspecialchars($arr_postVals['articleTitle'], ENT_QUOTES));
			$o_articleToUpdate->setArticleContent(htmlspecialchars($arr_postVals['articleContent'], ENT_QUOTES));
			$o_articleToUpdate->setCreateDate(new \DateTime("now"));
			$this->o_em->merge($o_articleToUpdate);
			$this->o_em->flush();
			//$this->viewArticles();
			fw_util_redirect('ViewArticles');
		}else{
			parent::start();
			parent::showNavi();
			$this->getSubNavi();
			$this->registry->template->s_mainAppDisplay = $o_updateArticleForm->getFormHtml();
			$this->registry->template->show('Skeleton.php');
		}
	}
	
	
	//pagination via ajax
	public function doArticlesPagination()
	{
		if($_SERVER['REQUEST_METHOD'] == 'GET'){
			$arr_request = $_GET;
		}else{
			$arr_request = $_POST;
		}
		
		//pagination
		if(isset($arr_request['iDisplayStart']) && isset($arr_request['iDisplayLength'])){
			//offset of displayed records
			$this->setOffset($arr_request['iDisplayStart']);
	
			//max amount of records to display
			$this->setMaxShown($arr_request['iDisplayLength']);
				
			//order by, sorting
			$this->arr_currPageObjects = $this->o_em->getRepository('Article')->getArticlesByPage(
				$this->getOffset(),
				$this->getMaxShown(),
				$arr_request['iSortCol_0'],
				$arr_request['sSortDir_0'],
				intval($arr_request['sEcho'])
			);
			fw_util_outputJson($this->arr_currPageObjects);
		}
	
	}
	
	private function setOffset($i_offset = 0)
	{
		if(trim($i_offset) != ''){
			if(is_numeric($i_offset)){
				$this->i_offset = (int)htmlspecialchars($i_offset);
			}
		}
	}
	
	private function setMaxShown($i_maxShown = 10)
	{
		if(trim($i_maxShown) != ''){
			if(is_numeric($i_maxShown)){
				$this->i_maxShown = (int)htmlspecialchars($i_maxShown);
			}
		}
	}
	
	private function getOffset()
	{
		return $this->i_offset;
	}
	
	private function getMaxShown()
	{
		return $this->i_maxShown;
	}
}
